package cn.ges.movie.util

import org.springframework.security.core.context.SecurityContextHolder

/**
 *
 * @author gespent@163.com
 * @date 2021/3/15 15:30
 */
class UserIdHelper {
    companion object {
        /**
         * 获取当前用户ID
         *
         * @since 2019年1月2日 12:03:39 加入空指针检查
         */
        fun getCurrentUserId(): String? {
            val context = SecurityContextHolder.getContext()
            if (context != null) {
                val authentication = context.authentication
                if (authentication != null) {
                    val principal = authentication.principal
                    if (principal != null) {
                        return principal as String
                    }
                }
            }
            return null
        }

        /**
         * 返回Long类型的userid
         *
         * @return 当用户未登录时, 返回null
         */
        fun getLongCurrentUserId(): Long? {
            val userId = getCurrentUserId()
            return if (userId != null && "anonymousUser" != userId) {
                userId.toLong()
            } else {
                null
            }
        }
    }
}